package com.syqc.monitor.ui.realalarm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.entity.AlarmDetail
import com.syqc.entity.AlarmMedia
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.TimeUtil

/**
 *@author joker
 *@time   2023/12/27 11:29
 *@desc
 */
class AlarmInfoVM : AutoDisposeViewModel() {
    private val _alarms = MutableLiveData<ArrayList<AlarmDetail>>()
    val alarms: LiveData<ArrayList<AlarmDetail>> = _alarms

    private val allAlarms = ArrayList<AlarmDetail>()

    private val _start = MutableLiveData<ArrayList<AlarmMedia>>()
    val start: LiveData<ArrayList<AlarmMedia>> = _start

    var plate: String = ""
    var catId: String = ""

    fun getAlarmByType(alarmType: String) {
        allAlarms.clear()
        toastLoading(true)
        ServiceHelper.getRepository().getAlarmDetail(alarmType).autoDispose(this)
            .subscribe({
                toastLoading(false)
                if (it.isNullOrEmpty()) {
                    toast(R.string.desc_no_about_data)
                    _alarms.postValue(it)
                    return@subscribe
                }
                allAlarms.addAll(it)
                _alarms.postValue(it)
            }, error)
    }

    private val searchAlarms = ArrayList<AlarmDetail>()
    fun search(key: String) {
        searchAlarms.clear()
        val upKey = key.uppercase()
        allAlarms.forEach {
            if (it.carPlate.uppercase().contains(upKey) || it.carName.uppercase()
                    .contains(upKey)
            ) searchAlarms.add(it)
        }
        _alarms.postValue(searchAlarms)
    }


    fun getAlarmInfo(startTime: String, alarmType: String) {
        toastLoading(true)
        ServiceHelper.getRepository().getAlarmMedia(
            catId,
            TimeUtil.instance.formatHm(startTime),
            alarmType
        ).autoDispose(this).subscribe({
            toastLoading(false)
            if (it.isNullOrEmpty()) {
                toast(R.string.desc_no_about_data)
                return@subscribe
            }
            _start.postValue(it)

        }, error)
    }
}